import * as xlsx from 'xlsx'
import { Request } from 'express';

// 上传excel并解析
export const uploadExcel = function (req: Request) {
  return new Promise((resolve, reject) => {
    if (!req.files || req.files.length === 0) {
      reject({ msg: '请选择Excel文件上传！' })
    }
    const { originalname, buffer } = req.files[0]
    if (!originalname.endsWith('xls') && !originalname.endsWith('xlsx')) {
      reject({ msg: 'Excel文件格式必须是xls或xlsx，请重新上传！' })
    }
    // 解析excel文件
    const workbook = xlsx.read(buffer, { type: 'buffer' })
    const sheet = workbook.Sheets[workbook.SheetNames[0]] // 选择第一个工作簿
    // { defval: '' } 单元格为空的话，值就默认给空字符串
    const result = xlsx.utils.sheet_to_json(sheet, { defval: '' })  
    if (result.length === 0) {
      reject({msg: '该Excel文件内容为空，请重新上传！'})
    }
    
    resolve(result)
  })
}